package com.wuliupai.delivery.wuliupaidelivery.fragment;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.activity.GrabOrderDetailActivity_;
import com.wuliupai.delivery.wuliupaidelivery.activity.GrabOrderListActivity;
import com.wuliupai.delivery.wuliupaidelivery.adapter.OrderListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.ui.RefreshAndLoadLayout;
import com.wuliupai.delivery.wuliupaidelivery.utils.CommonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 * Descriptions：
 * <p>
 * Author：ChenME
 * Date：2018/2/3
 * Email：ibelieve1210@163.com
 */

@EFragment(R.layout.fragmet_order_list)
public class OrderPickUpFragment extends Fragment {

    @Bean(CommonUtils.class)
    CommonUtils cUtils;

    @ViewById(R.id.recyclerView)
    RecyclerView recyclerView;
    @ViewById(R.id.swipe_layout)
    RefreshAndLoadLayout swipe_layout;
    @ViewById(R.id.tv_noDataTips)
    TextView tv_noDataTips;

    private GrabOrderListActivity _activity;

    private List<OrderBean> dataList;
    private OrderListAdapter adapter;

    private int pageIndex;//页面索引
    private String area = "";
    private String CollectGoods = "0"; // 0-揽收，1-派送

    private LocalBroadcastManager lbm;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            area = intent.getStringExtra("area");
            loadData(null, true);
        }
    };

    @AfterViews
    void onPageStart() {
        _activity = (GrabOrderListActivity) getActivity();
        initRefreshAndRecyclerView();
        initBroadcastReceiver();
    }

    /**
     * 初始化广播
     */
    private void initBroadcastReceiver() {
        lbm = LocalBroadcastManager.getInstance(_activity);
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastChannels.Channel_RefreshOrderListByArea);
        lbm.registerReceiver(receiver, filter);
    }

    /**
     * 绑定列表数据
     */
    private void initRefreshAndRecyclerView() {
        cUtils.initRefreshAndLoadLayout(swipe_layout);
        dataList = new ArrayList<>();
        adapter = new OrderListAdapter(_activity, dataList);
        recyclerView.setLayoutManager(new LinearLayoutManager(_activity));
        recyclerView.setAdapter(adapter);

        adapter.setOnAdapterClickListener(new OrderListAdapter.OnAdapterClickListener() {
            @Override
            public void onItemClick(int pos) {
                OrderBean  bean = dataList.get(pos);
                GrabOrderDetailActivity_.intent(_activity).warehouseId(bean.getWarehouseId()).orderId(bean.getOrderId()).collectGoods(CollectGoods).start();
            }

            @Override
            public void onItemLongClick(int pos) {

            }

            @Override
            public void onGrabBtnClick(int pos) {
                OrderBean bean = dataList.get(pos);
                grabBtnClick(bean.getOrderId(), bean.getWarehouseId());
            }
        });

        // 设置下拉刷新监听器
        swipe_layout.setOnRefreshListener(() -> {
            if (swipe_layout.isLoading()) {
                swipe_layout.setRefreshing(false);
            } else {
                loadData(swipe_layout, true);
            }
        });

        // 加载监听器
        swipe_layout.setOnLoadListener(() -> {
            loadData(swipe_layout, false);
        });
    }

    /**
     * 点击抢单按钮
     *
     * @param orderId
     */
    private void grabBtnClick(String orderId, String warehouseId) {
        OrderBean requestBean = new OrderBean();
        requestBean.setOrderId(orderId);
        requestBean.setWarehouseId(warehouseId);
        requestBean.setCollectGoods(CollectGoods);

        String requestJson = JsonUtils.createJsonString(requestBean);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            _activity.callNet(_activity, InterfaceNet.Net_GrabOrder, requestAes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    Intent intent = new Intent(BroadcastChannels.Channel_GrabOrderSuccess);
                    LocalBroadcastManager.getInstance(_activity).sendBroadcast(intent);
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载数据
     *
     * @param swipeLayout
     * @param isClear
     */
    private void loadData(RefreshAndLoadLayout swipeLayout, final boolean isClear) {
        int si = pageIndex;
        if (isClear) {
            si = pageIndex = 0;
        }

        OrderBean requestBean = new OrderBean(si + "", Value.listCount + "");
        requestBean.setStatus("1");
        requestBean.setCityName(area);

        String requestJson = JsonUtils.createJsonString(requestBean);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            _activity.callNet(_activity, InterfaceNet.Net_GetGrabOrderList, requestAes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {

                    _activity.clearRefresh(swipeLayout, isClear);
                    showNoDataTips(false);

                    if (!StringUtils.isEmpty(content)) {
                        pageIndex += Value.listCount;

                        if (isClear) {//刷新
                            dataList.clear();
                        }

                        Object obj = JsonUtils.parseJsonString(content, OrderBean.class);
                        if (obj instanceof OrderBean) {
                            OrderBean bean = (OrderBean) obj;
                            dataList.addAll(bean.infolist);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                    _activity.clearRefresh(swipeLayout, isClear);
                    dataList.clear();
                    adapter.notifyDataSetChanged();
                    showNoDataTips(true);
                }

                @Override
                public void onDataEnd(String content) {
                    showNoDataTips(false);
                    _activity.clearRefresh(swipeLayout, isClear);
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);
                    showNoDataTips(false);
                    _activity.clearRefresh(swipeLayout, isClear);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示没有数据的提示
     *
     * @param isShow 是否显示
     */
    private void showNoDataTips(boolean isShow) {
        tv_noDataTips.setVisibility(isShow ? View.VISIBLE : View.GONE);
        if (isShow) {
            tv_noDataTips.setText(Html.fromHtml(new StringBuilder().append("「<font color='#FF9831'>").append(area).append("</font>」").append("暂无数据，<br/>请点击右上角切换地区重试！").toString()));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lbm.unregisterReceiver(receiver);
    }
}
